//
//  SetTabVC.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/6.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit
import Photos
import MobileCoreServices
import AssetsLibrary
import AVKit

class SetTabVC: UITableViewController {


    @IBOutlet weak var userHeader: BCUIImageView!
    @IBOutlet weak var userName: UILabel!
    @IBOutlet weak var userPhone: UILabel!
    @IBOutlet weak var cacheText: UILabel!
    @IBOutlet weak var connectState: UILabel!
    
    private let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        userHeader.layer.cornerRadius = 9
        userHeader.layer.masksToBounds = true
        setUIData()
        userMessageObserver()
        deviceConnectStaeObserver()
    }
    // 头像点击
    @IBAction func headerBtnClick(_ sender: UIButton) {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        let actionCamera = UIAlertAction.init(title: "拍照", style: .default) { (action) in
            self.selectByCamera()
        }
        
        let actionPhoto = UIAlertAction.init(title: "从手机照片中选择", style: .default) { (action) in
            self.selectFromPhoto()
        }
        
        alert.addAction(actionCancel)
        alert.addAction(actionCamera)
        alert.addAction(actionPhoto)
        self.present(alert, animated: true, completion: nil)
    }
    // 修改m昵称
    @IBAction func changeNameClik(_ sender: UIButton) {
        self.navigationController?.pushViewController(SetNameVC(), animated: true)
    }
    
    //连接设备
    @IBAction func connectDevice(_ sender: UIButton) {

        if BCUserManager.shareManager.BlueTooth_isOpen.value {
            let vc = UIStoryboard.viewController(from: .SetSB, viewControllerClass: ConnectDeviceVC.self)
            self.navigationController?.pushViewController(vc, animated: true)
        } else {
            self.showTipMsg("手机蓝牙不可用,请检查是否打开", time: 1)
        }
        
    }
     //清除缓存
    @IBAction func clearClick(_ sender: UIButton) {
        if BCCacheTool.clearCache() {
            self.showTipMsg("缓存已清除", time: 1)
            cacheText.text = BCCacheTool.cacheSize
         }else {
            self.showTipMsg("缓存清除失败", time: 1)
        }
    }
    //退出登录
    @IBAction func exitLoginClick(_ sender: UIButton) {
        exitLogin()
    }
    
}

extension SetTabVC {
    // 蓝牙设备的连接监控
    fileprivate func deviceConnectStaeObserver() {
        BCUserManager.shareManager.BlueTooth_isOpen.asDriver()
            .drive(onNext: { [weak self] (state) in
                self?.setDeviceConnectStae(state)
            }).disposed(by: disposeBag)
    }
    // 个人信息更新监控
    fileprivate func userMessageObserver() {
        BCUserManager.shareManager.Update_Message.asDriver()
            .drive(onNext: { [weak self] (state) in
                self?.setUIData()
            }).disposed(by: disposeBag)
    }
    // z设置界面的数据
    fileprivate func setUIData() {
        self.fd_prefersNavigationBarHidden = true //隐藏导航栏
        userName.text = BCUserManager.shareManager.user_name
        userPhone.text = BCUserManager.shareManager.user_phone
        cacheText.text = BCCacheTool.cacheSize
        let urlStr = BCUserManager.shareManager.user_photo_url
        let url = URL(string: urlStr ?? "")
        userHeader.kf.setImage(with: url, placeholder: UIImage(named: "user_head"))
    }
    // 设置设备连接的状态
    fileprivate func setDeviceConnectStae( _ blueTooth: Bool) {
        if blueTooth , (Gloab_Connect_Device != nil) {
            connectState.text = "已连接"
            connectState.textColor = UIColor.hex(hexString: "#7F899A")
        } else {
            connectState.text = "未连接"
            connectState.textColor = UIColor.hex(hexString: "#F14970")
        }
    }
    
    func exitLogin() {
        let alertVC = UIAlertController(title: nil, message: "确认退出?", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertVC.addAction(cancelAction)
        let enterAction = UIAlertAction(title: "确定", style: .default) { (action) in
            UIApplication.shared.delegate?.window??.rootViewController = UIStoryboard.viewController(from: .LoginSB, viewControllerClass: StudyLoginVC.self)
            WebSocketManager.sharedInstance().logOutConnect() //退出WebSocket连接
            BCUserManager.shareManager.isLogin = false
        }
        enterAction.setTextColor(UIColor.hex(hexString: "#F14970"))
        alertVC.addAction(enterAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    fileprivate func uploadPhoto(photo: UIImage) {
        //生成唯一数
        let soleStr = ProcessInfo.processInfo.globallyUniqueString
        //头部字段： X-Key-Filekey，这个字段为上传文件的唯一标识符
        let fileKey = "\(BCUserManager.shareManager.user_uid ?? "")_avatar_\(soleStr.md5).jpg"
        // 待上传图片的二进制数据
        let imageData = UIImage.bcCompressImage(image: photo, maxLength: 2*1024)
        if let data = imageData {
            let target = BCAPI.upload_photo(iamgeData: data, fileKey: fileKey)
            ApiLoadingProvider.request(target, model: BaseModel.self) { (data) in
                
            }
        }
        
    }
}

// MARK: 相机相册相关
extension SetTabVC : UIImagePickerControllerDelegate , UINavigationControllerDelegate {
   // 拍照
   fileprivate func selectByCamera()  {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .camera //调用摄像头
        imagePicker.cameraDevice = .rear //后置摄像头
        imagePicker.cameraCaptureMode = .photo //拍照
        imagePicker.allowsEditing = true //允许编辑
        imagePicker.delegate = self
        imagePicker.mediaTypes = [kUTTypeImage as String]
        self.show(imagePicker, sender: nil)
    }
    /**
     * 从相册中选择图片
     */
    fileprivate func selectFromPhoto(){
        PHPhotoLibrary.requestAuthorization {[unowned self] (status) -> Void in
            DispatchQueue.main.async {
                switch status {
                case .authorized:
                    self.showLocalPhotoGallery()
                    break
                default:
                    self.showNoPermissionDailog()
                    break
                }
            }
        }
    }
    
    /**
     * 用户相册未授权，Dialog提示
     */
    private func showNoPermissionDailog(){
        let alert = UIAlertController.init(title: nil, message: "没有打开相册的权限", preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
    
    // MARK: 打开本地相册
    func showLocalPhotoGallery()  {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .photoLibrary //调用相册
        imagePicker.allowsEditing = true //允许编辑
        imagePicker.delegate = self
        imagePicker.navigationBar.isTranslucent = false //解决偏移的问题
        imagePicker.mediaTypes = [kUTTypeImage as String]
        self.show(imagePicker, sender: nil)
    }
    // MARK: 拍照的代理方法
    // 退出拍照
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //图片选取
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        let mediaType = info[.mediaType] as! String
        guard mediaType == kUTTypeImage as String else {
            return
        }
        var image: UIImage?
        if picker.isEditing == true { // 拍照图片运行编辑，则优先尝试从编辑后的类型中获取图片
            image = info[.originalImage] as? UIImage
        }else{
            image = info[.editedImage] as? UIImage
        }
        userHeader.image = image //头像赋值
        uploadPhoto(photo:image ?? UIImage())
        // 拍照的图片保存的到本地相册
        guard let rImage = image , picker.sourceType == .camera else {
            return
        }
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: rImage)
        }, completionHandler: nil)
        
    }

}


extension UIAlertAction {
    /// 设置文字颜色
    func setTextColor(_ color: UIColor) {
        let key = "_titleTextColor"
        self.setValue(color, forKey: key)
    }
    
}
